<!DOCTYPE html>
<html>
<head>    
    <title>BodyPix Demo 01 - 加载图片, 然后帮图片抠出人物的轮廓</title>
    <!-- <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script> -->
    <script src="/static/js/tf@3.29.1.min.js"></script>    
    <!-- <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix"></script> -->
    <script src="/static/js/body-pix@2.2.0.min.js"></script>
    
</head>
<body>
    <canvas id="canvas0"></canvas>

    <script>
        function loadImage(src) {
            const image = new Image();

            const canvas = document.getElementById('canvas0');
            const ctx = canvas.getContext('2d');

            image.crossOrigin = '';
            
            image.addEventListener('load', ()=>{
                canvas.width = image.width;
                canvas.height = image.height;
                ctx.drawImage(image, 0, 0);
                console.log('draw Image to Canvas');
                execute();
            });

            image.src = src;
        }

        async function execute() {
            const canvas = document.getElementById('canvas0');
            const ctx = canvas.getContext('2d');

            console.log('load bodyPix');
            const net = await bodyPix.load({
                architecture: 'MobileNetV1',
                outputStride: 16,
                multiplier: 0.75,
                quantBytes: 2
            });

            const { data:map } = await net.segmentPerson(canvas, {internalResolution: 'medium'});
            console.log('calc map:', map);

            const { data:imgData } = ctx.getImageData(0, 0, canvas.width, canvas.height);

            const newImg = ctx.createImageData(canvas.width, canvas.height);
            const newImgData = newImg.data;

            const whiteColor = [0, 0, 0, 0]; // TODO 透明

            for(let i=0; i<map.length; i++) 
            {
                // const [r, g, b, a] = [imgData[i*4], imgData[i*4+1], imgData[i*4+2], imgData[i*4+3]];
                // [newImgData[i*4], newImgData[i*4+1], newImgData[i*4+2], newImgData[i*4+3]] = !map[i] ? [255,255,255,0] : [r,g,b,a];

                if(map[i])
                {
                    // 当前像数是人, 保留当前的颜色
                    [newImgData[i*4], newImgData[i*4+1], newImgData[i*4+2], newImgData[i*4+3]] = [imgData[i*4], imgData[i*4+1], imgData[i*4+2], imgData[i*4+3]];
                }
                else
                {
                    // 当前像数不是人, 设置为透明
                    [newImgData[i*4], newImgData[i*4+1], newImgData[i*4+2], newImgData[i*4+3]] = whiteColor;
                }
            }

            console.log('draw mask');
            ctx.putImageData(newImg, 0, 0);

            // net.dispose();
        }

        loadImage(`static/img/Demo01.png`);
    </script>
</body>
</html>